package com.qys.livesMall.open.mail.factory;

import com.qys.livesMall.open.mail.config.MailConfig;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;

@Slf4j
public class SessionFactory {

    public static Session createSession()  {
        MailConfig config= MailConfig.get();

        // 邮箱账号和密码(授权密码)
        // SMTP服务器的连接信息
        Properties props = new Properties();
        props.put("mail.smtp.host", config.getHost()); // SMTP主机号
        props.put("mail.smtp.port", config.getPort()); // 主机端口号
        props.put("mail.smtp.auth", config.getAuth()); // 是否需要认证
        props.put("mail.smtp.starttls.enable", config.getStarttlsEnable()); // 启用TLS加密

//关键Java代码如下：
//QQ存在一个特性设置SSL加密
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory("TLSv1.2");
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
            props.put("mail.smtp.socketFactory.port", "465");
            //props.put("mail.smtp.localhost", config.getHost());

            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }catch (Exception  e){
            log.error("mail配置失败",e);
        }

        // 创建Session
        // 参数1：SMTP服务器的连接信息
        // 参数2：用户认证对象(Authenticator接口的匿名实现类)
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUserName(), config.getPassword());
            }
        });

        // 开启调试模式
        session.setDebug(true);

        return session;
    }
}
